package cn.dujc.superkid.api;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;

import cn.dujc.core.ui.IBaseUI;
import cn.dujc.core.util.ContextUtil;
import cn.dujc.core.util.ToastUtil;
import cn.dujc.superkid.activities.LoginActivity;
import cn.dujc.superkid.utils.Preferences;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public abstract class ResultCallBack<T extends Result> implements Callback<T> {
    private static final String TAG = "ResultCallBack";
    private Context mContext;

    public ResultCallBack(Context context) {
        mContext = context;
    }

    //public ResultCallBack() { }

    @Override
    public void onResponse(@NonNull Call<T> call, @NonNull Response<T> response) {
        if (response.isSuccessful()) {
            final T body = response.body();
            if (body != null) {
                if (body.getCode() == 200) {
                    onSuccessCallback(200, body);
                } else {//在接口正常返回数据时，使用接口返回的200、400、403等错误码作为code
                    onFailureCallback(body.getCode(), body.getMsg());
                }
                return;
            }
        }
        final int code = response.code();//在接口什么都没返回（即无网络、超时）时，使用http的code
        onFailureCallback(code, "网络连接错误");
    }

    @Override
    public void onFailure(@NonNull Call<T> call, @NonNull Throwable t) {
        onFailureCallback(0, t.getLocalizedMessage());
    }

    public abstract void onSuccessCallback(int code, T body);

    public void onFailureCallback(int code, String msg) {
        if (mContext != null) {
            if (!TextUtils.isEmpty(msg)) ToastUtil.showToast(mContext, msg);
            Log.d(TAG, "onFailureCallback: msg="+msg);
            if (code == 403) {//被挤下线是403，大概登录失效都是403
                Preferences.getInstance().saveLoginResult(mContext, null);
                if (mContext instanceof IBaseUI) {//如果是用我的activity或fragment的话，直接调它自带的starter方法
                    ((IBaseUI) mContext).starter().go(LoginActivity.class, true);
                } else {//否则采用普通的跳转，并在可能的情况下关闭当前activity
                    mContext.startActivity(new Intent(mContext, LoginActivity.class));
                    final Activity activity = ContextUtil.getActivity(mContext);
                    if (activity != null) activity.finish();
                }
            }
        }
    }

}